import {
	Button,
	Switch,
	Form,
	Row,
	Col,
	Input,
	Select,
	message,
	Cascader,
	TreeSelect,
} from 'antd'
import React, {useState, useEffect, useRef} from 'react'
import {history, connect} from 'umi'
import {PlusOutlined} from '@ant-design/icons'
import {
	ActionType,
	EditableFormInstance,
	ProColumns,
	EditableProTable,
} from '@ant-design/pro-components'
import moment from 'moment'
import styles from './index.less'
import {
	getAllCitys,
	getCommonCompanyCity,
	getCompany,
	getGenerateNumber,
} from '@/service/common'
import Modal from '@/components/Modal'
import {
	addWarehousearchives,
	editWarehousearchives,
	warehousearchivesInfo,
} from '@/service/storage/archives'
import {translateDataToTree} from '@/utils/common'
import {getDict} from '@/service/common/dict'
import OperationRecord from '@/components/OperationRecord'

const {TextArea} = Input

type DataSourceType = {
	id?: string
	costType: string
	price: string
	startTime: string
	endTime: string
	effectiveFlag: string
	ruleDescribe: string
}

// 城市
const cityNames = {
	label: 'name',
	value: 'id',
	children: 'cityInfoList',
}

const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const add = (props: any) => {
	const {query} = props.location
	const [form] = Form.useForm()
	const [type, setType] = useState<string>()
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [warehouseType, setWarehouseType] = useState<string>('')
	const [formData, setFormData] = useState<any>({})
	const actionRef = useRef<ActionType>()
	const editorFormRef = useRef<EditableFormInstance<DataSourceType>>()
	const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])
	const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([])
	const [companyData, setCompanyData] = useState([])
	const [cityName, setCityName] = useState('')
	const [dictData, setDictData] = useState<any>()
	// 城市数据
	const [citysList, setCitysList] = useState([])
	const [companyCitysList, setCompanyCitysList] = useState<any[]>([])
	const [startDate, setStartDate] = useState<any>(new Date())
	const [btnLoading, setBtnLoading] = useState(false)

	/** 获取城市列表 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.data) {
				setCitysList(() => res.data)
			}
		})
	}
	/** 获取所属公司数据 */
	const onCompany = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			const list = translateDataToTree(res.data)
			setCompanyData(list as any)
		})
	}
	useEffect(() => {
		onCompany()
	}, [props?.user?.orgId])

	const onCompanyCity = (value: string | number) => {
		getCommonCompanyCity({merchantId: value})
			.then((res: any) => {
				setCompanyCitysList(res.data)
				if (!query?.id) {
					if (res?.data?.length === 1) {
						form.setFieldsValue({cityId: res?.data?.[0]?.cityId})
					} else {
						form.setFieldsValue({cityId: undefined})
					}
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	// 根据路由判断当前页面状态
	useEffect(() => {
		getCitysFun()
		getDict(
			{
				dictKeys: ['Warehouse_Type'],
			},
			(res: any) => {
				setDictData(res)
			},
		)
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('add')) {
			setType('add')
			getGenerateNumber('CCDA').then((res: any) => {
				form.setFieldsValue({warehouseCode: res.data})
			})
		} else {
			setType('edit')
		}
	}, [])

	useEffect(() => {
		if (query?.id) {
			warehousearchivesInfo(query?.id).then((res: any) => {
				if (res?.data) {
					onCompanyCity(res.data.orgId)
					const provincialUrbanAreas = res.data?.provincialUrbanAreas
						?.split(',')
						.map(Number)
					form.setFieldsValue({
						...res.data,
						provincialUrbanAreas: res.data?.provincialUrbanAreas
							? provincialUrbanAreas
							: undefined,
						warehouseType: res.data?.warehouseType.toString(),
						startUpStatus: res.data?.startUpStatus === 1,
					})
					setCityName(res.data?.cityName)
					setWarehouseType(res.data?.warehouseType.toString())
					setDataSource(res.data.rulesList)
				}
			})
		} else {
			form.setFieldsValue({orgId: props?.user?.orgId})
			onCompanyCity(props?.user?.orgId)
		}
	}, [query])

	const onSave = async () => {
		const value = await form.validateFields()
		const newData = [...dataSource]
		dataSource.forEach((item, index) => {
			delete newData[index].id
		})
		if (value) {
			setFormData({
				...value,
				provincialUrbanAreas: value?.provincialUrbanAreas
					? value?.provincialUrbanAreas.toString()
					: '',
				warehouseType: Number(value.warehouseType),
				startUpStatus: value?.startUpStatus ? 1 : 2,
				rulesList: newData,
				cityName,
			})
			setIsModalOpen(true)
		}
	}

	const onSubmit = () => {
		setBtnLoading(true)
		let request: any
		if (query?.id) {
			// 编辑
			request = editWarehousearchives({...formData, id: query.id})
		} else {
			request = addWarehousearchives(formData)
		}
		request
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
				setBtnLoading(false)
			})
			.catch((err: any) => {
				message.error(err)
				setBtnLoading(false)
			})
	}

	const columns: ProColumns<DataSourceType>[] = [
		{
			title: '费用模式',
			key: 'costType',
			dataIndex: 'costType',
			valueType: 'select',
			valueEnum: {
				'1': {text: '按车位'},
				'2': {text: '按月固定租金'},
			},
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '价格（按车位，输入每个车位单价，按固定价格，输入每月固定的租金）',
			dataIndex: 'price',
			key: 'price',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
			width: 200,
		},
		{
			title: '开始时间',
			dataIndex: 'startTime',
			key: 'startTime',
			valueType: 'date',
			fieldProps: {
				onChange: (value: moment.MomentInput) => {
					setStartDate(moment(value).format('YYYY-MM-DD'))
				},
				disabledDate: (current: any) => {
					const defaults = moment(current).format(
						'YYYY-MM-DD HH:mm:ss',
					)
					return defaults < moment().format('YYYY-MM-DD 00:00:00')
				},
			},
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '结束时间',
			dataIndex: 'endTime',
			key: 'endTime',
			valueType: 'date',
			fieldProps: {
				disabledDate: (current: any) => {
					const defaults = moment(current).format(
						'YYYY-MM-DD HH:mm:ss',
					)
					return (
						defaults <
						moment(startDate).format('YYYY-MM-DD 00:00:00')
					)
				},
			},
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '是否有效',
			dataIndex: 'effectiveFlag',
			key: 'effectiveFlag',
			valueType: 'select',
			valueEnum: {
				'1': {text: '有效'},
				'2': {text: '无效'},
			},
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '描述',
			dataIndex: 'ruleDescribe',
		},
		{
			title: '操作',
			valueType: 'option',
			width: 120,
			hideInTable: type === 'view',
			render: (text, record, index) => [
				<>
					{record.effectiveFlag === '1' ? (
						<Button
							type="link"
							key="editable"
							onClick={() => {
								const newData = [...dataSource]
								newData.forEach((item, inx) => {
									if (inx === index) {
										newData[inx].effectiveFlag = '2'
									}
								})
								setDataSource(newData)
							}}>
							终止
						</Button>
					) : (
						''
					)}
				</>,
				<Button
					type="link"
					key="delete"
					onClick={() => {
						setDataSource(
							dataSource.filter((item) => item.id !== record.id),
						)
					}}>
					删除
				</Button>,
			],
		},
	]
	return (
		<div className={styles.add}>
			<div className={styles.title}>基础信息</div>
			<Form
				form={form}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '140px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off"
				disabled={type === 'view'}>
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="代码"
							name="warehouseCode"
							rules={[{required: true}]}>
							<Input placeholder="请输入" disabled />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="名称"
							name="warehouseName"
							rules={[{required: true}]}>
							<Input placeholder="请输入" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="仓库类型"
							name="warehouseType"
							rules={[{required: true}]}>
							<Select
								placeholder="请选择"
								allowClear
								fieldNames={{
									value: 'dictKey',
									label: 'dictValue',
								}}
								onChange={(value) => setWarehouseType(value)}
								options={dictData?.Warehouse_Type}
								disabled={type !== 'add'}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="所属公司"
							name="orgId"
							rules={[{required: true}]}>
							<TreeSelect
								showSearch
								style={{width: '100%'}}
								treeNodeFilterProp="name"
								dropdownStyle={{
									maxHeight: 400,
									overflow: 'auto',
								}}
								placeholder="请选择"
								allowClear
								treeDefaultExpandAll
								fieldNames={fieldNames}
								treeDataSimpleMode
								treeData={companyData}
								disabled={type !== 'add'}
								onChange={(value) => {
									onCompanyCity(value)
								}}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="城市"
							name="cityId"
							rules={[{required: true}]}>
							<Select
								placeholder="请选择"
								allowClear
								fieldNames={{
									value: 'cityId',
									label: 'cityName',
								}}
								onChange={(value, key) => {
									setCityName(key?.cityName)
								}}
								options={companyCitysList}
								disabled={type !== 'add'}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							name="startUpStatus"
							label="启动"
							valuePropName="checked">
							<Switch />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="联系人姓名"
							name="contactName"
							rules={[{required: true, max: 6}]}>
							<Input placeholder="请输入" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="联系人手机号码"
							name="contactPhone"
							rules={[
								{required: true},
								{
									pattern:
										/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
									message: '请输入正确的手机号',
								},
							]}>
							<Input placeholder="请输入" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item label="注册城市" name="provincialUrbanAreas">
							<Cascader
								fieldNames={cityNames}
								options={citysList}
								placeholder="请选择"
							/>
						</Form.Item>
					</Col>
					<Col span={16}>
						<Form.Item
							label="详细地址"
							name="detailedAddress"
							rules={[{required: true, max: 100}]}>
							<Input placeholder="请输入" />
						</Form.Item>
					</Col>
					<Col span={16}>
						<Form.Item label="备注" name="remark">
							<TextArea
								maxLength={200}
								placeholder="请输入（最多200个字）"
								autoSize={{minRows: 3, maxRows: 6}}
							/>
						</Form.Item>
					</Col>
				</Row>
			</Form>
			{warehouseType === '1' ? (
				<>
					{' '}
					<div className={styles.title}>停车费用规则</div>
					{type !== 'view' ? (
						<Button
							icon={<PlusOutlined />}
							type="primary"
							ghost
							size="small"
							style={{marginBottom: '12px'}}
							onClick={() => {
								actionRef.current?.addEditRecord?.({
									id: (Math.random() * 1000000).toFixed(0),
								})
							}}>
							新增
						</Button>
					) : (
						''
					)}
					<EditableProTable<DataSourceType>
						bordered
						rowKey="id"
						actionRef={actionRef}
						editableFormRef={editorFormRef}
						// 关闭默认的新建按钮
						recordCreatorProps={false}
						columns={columns}
						value={dataSource}
						onChange={(value) => {
							const data = value[value.length - 1]
							const status = dataSource.find((item) => {
								const start =
									moment(data.startTime) >=
										moment(item.startTime) &&
									moment(data.startTime) <=
										moment(item.endTime)
								const end =
									moment(data.endTime) >=
										moment(item.startTime) &&
									moment(data.endTime) <= moment(item.endTime)
								return start || end
							})
							if (!status) {
								setDataSource(value)
							} else {
								message.warning(
									'不允许新增两个时间上有交叉的停车场计费规则',
								)
							}
						}}
						editable={{
							form,
							editableKeys,
							onSave: async () => true,
							onChange: setEditableRowKeys,
							actionRender: (row, config, dom) => [
								dom.save,
								dom.cancel,
							],
						}}
					/>
				</>
			) : (
				''
			)}
			{type === 'view' ? (
				<>
					<div className={styles.title}>操作记录</div>
					<OperationRecord businessId={query?.id} businessType={36} />
				</>
			) : (
				''
			)}

			<div className={styles.wrap}>
				{type === 'view' ? (
					<Button
						onClick={() => {
							history.go(-1)
						}}>
						返回
					</Button>
				) : (
					<>
						{' '}
						<Button
							type="primary"
							htmlType="submit"
							onClick={() => {
								onSave()
							}}>
							保存
						</Button>
						<Button
							onClick={() => {
								history.go(-1)
							}}>
							取消
						</Button>
					</>
				)}
			</div>
			<Modal
				text="确定要保存吗？请仔细核对所填信息"
				loading={btnLoading}
				onSubmit={onSubmit}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(add)
